package com.zmx.doctor.view.activity;

import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.wang.adapters.interfaceabstract.OnItemClickListener;
import com.zmx.doctor.BaseActivity;
import com.zmx.doctor.R;
import com.zmx.doctor.adapter.ExpertTeamDoctorAdapter;
import com.zmx.doctor.adapter.OrderItemAdapter;
import com.zmx.doctor.okhttp.OkHttp3ClientManager;
import com.zmx.doctor.pojo.ExpertTeamDoctor;
import com.zmx.doctor.pojo.PatientOrder;
import com.zmx.doctor.utils.AllUtil;
import com.zmx.doctor.view.util.MySharedPreferences;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;

public class ExpertTeamDetailActivity extends BaseActivity {

    @BindView(R.id.team_name)
    TextView teamName;
    @BindView(R.id.editor)
    ImageView editor;
    @BindView(R.id.team_expertise)
    TextView teamExpertise;
    @BindView(R.id.team_doctor_head)
    CircleImageView teamDoctorHead;
    @BindView(R.id.team_doctor_names)
    TextView teamDoctorNames;
    @BindView(R.id.team_doctor_title)
    TextView teamDoctorTitle;
    @BindView(R.id.team_doctor_depment)
    TextView teamDoctorDepment;
    @BindView(R.id.doctor_recycler)
    RecyclerView doctorRecycler;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.add_button)
    Button addButton;
    @BindView(R.id.button_layout)
    LinearLayout buttonLayout;
    @BindView(R.id.no_data)
    TextView no_data;

    private String team_id;

    private ExpertTeamDoctorAdapter doctor_adapter;
    private List<ExpertTeamDoctor> doctors;
    private List<ExpertTeamDoctor> ds;

    private OrderItemAdapter adapter;
    private List<PatientOrder> lists;

    private Integer listPosition;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_expert_team_detail;
    }

    @Override
    protected void initViews() {

        ButterKnife.bind(this);
        setToolbar(R.id.tool_bar);
        team_id = this.getIntent().getStringExtra("team_id");

        doctorRecycler.setLayoutManager(new LinearLayoutManager(mActivity));

        recyclerView.setLayoutManager(new LinearLayoutManager(mActivity));
        adapter = new OrderItemAdapter(mActivity);
        recyclerView.setAdapter(adapter);
        lists = new ArrayList<>();
        adapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            protected void onItemClick(View view, int listPosition) {

                Intent intent = new Intent(mActivity, OrderDetailsActivity.class);
                intent.putExtra("ask_id", lists.get(listPosition).getId() + "");
                intent.putExtra("type", "0");
                intent.putExtra("patient_id", lists.get(listPosition).getPatient_id() + "");
                startActivity(intent);

            }
        });


        getData();
    }

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {

        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);

            switch (msg.what) {

                case 1:

                    try {

                        JSONObject object = new JSONObject(msg.obj.toString());

                        JSONObject info = object.getJSONObject("info");

                        teamName.setText(info.getString("name"));
                        teamExpertise.setText(info.getString("describe"));

                        int logo = 0;

                        if (Integer.parseInt(MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.uid, "")) == info.getInt("member_id")) {

                            buttonLayout.setVisibility(View.VISIBLE);
                            editor.setVisibility(View.VISIBLE);
                            logo = 1;

                        } else {

                            buttonLayout.setVisibility(View.GONE);
                            editor.setVisibility(View.GONE);
                            logo = 0;

                        }

                        doctor_adapter = new ExpertTeamDoctorAdapter(mActivity, logo, handler);
                        doctorRecycler.setAdapter(doctor_adapter);
                        doctors = new ArrayList<>();

                        JSONArray user = object.getJSONArray("user");
                        Gson gson = new Gson();
                        for (int i = 0; i < user.length(); i++) {

                            JSONObject doctor = user.getJSONObject(i);


                            if (doctor.getInt("captain") == 1) {

                                teamDoctorNames.setText(doctor.getString("name"));
                                teamDoctorDepment.setText(doctor.getString("hosp_name") + " " + doctor.getString("class_name"));
                                teamDoctorTitle.setText(doctor.getString("title_name"));
                                Glide.with(mActivity).load(doctor.getString("avatar")).into(teamDoctorHead);

                            } else {

                                ExpertTeamDoctor td = gson.fromJson(doctor.toString(), ExpertTeamDoctor.class);
                                doctors.add(td);

                            }


                        }
                        doctor_adapter.setListAndNotifyDataSetChanged(doctors);
                        if (doctors.size() > 0) {

                            no_data.setVisibility(View.GONE);

                        } else {

                            no_data.setVisibility(View.VISIBLE);
                        }

                        JSONArray array = new JSONArray(object.getString("ask"));
                        for (int i = 0; i < array.length(); i++) {

                            JSONObject jsonObject = array.getJSONObject(i);
                            PatientOrder order = gson.fromJson(jsonObject.toString(), PatientOrder.class);
                            lists.add(order);

                        }

                        adapter.setListAndNotifyDataSetChanged(lists);//就是设置list然后刷新

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }


                    break;

                case 2:

                    listPosition = msg.arg1;

                    String user_id = msg.obj.toString();

                    AlertDialog.Builder builder = new AlertDialog.Builder(mActivity);
                    builder.setTitle("提示：");
                    builder.setMessage("是否要移除该医生？");

                    //设置确定按钮
                    builder.setNegativeButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                            outUser(user_id);
                        }
                    });
                    //设置取消按钮
                    builder.setPositiveButton("容我再想想", null);
                    //显示提示框
                    builder.show();

                    break;

                case 3:

                    try {

                        JSONObject object = new JSONObject(msg.obj.toString());

                        Toast(object.getString("msg"));

                        if (object.getInt("code") == 1) {

                            doctors.remove(doctors.get(listPosition));
                            doctor_adapter.notifyItemRemoved(listPosition);
                            doctor_adapter.notifyItemRangeRemoved(listPosition, doctors.size());

                        }


                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    break;
                case 4:


                    try {

                        JSONObject jsonObject = new JSONObject(msg.obj.toString());
                        Toast(jsonObject.getString("msg"));
                        if (jsonObject.getInt("code") == 1){
                            teamExpertise.setText(s_value);
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    break;
            }

        }
    };

    public void getData() {

        List<String> ls = new ArrayList<>();
        ls.add(team_id);
        //请求网络
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("sign", AllUtil.md5(sing(ls)));
        params.put("token", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.token, ""));
        params.put("uid", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.uid, ""));
        params.put("ts", System.currentTimeMillis() / 1000); // 当前时间戳
        params.put("cmd", "teamHome");
        params.put("data[team_id]", team_id);
        OkHttp3ClientManager.getInstance().NetworkRequestMode("http://zmx.123xk.cn/admin/api.team/entry", params, handler, 1, 404);

    }

    public void outUser(String user_id) {

        List<String> ls = new ArrayList<>();
        ls.add(team_id);
        ls.add(user_id);
        //请求网络
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("sign", AllUtil.md5(sing(ls)));
        params.put("token", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.token, ""));
        params.put("uid", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.uid, ""));
        params.put("ts", System.currentTimeMillis() / 1000); // 当前时间戳
        params.put("cmd", "outUser");
        params.put("data[team_id]", team_id);
        params.put("data[user_id]", user_id);
        OkHttp3ClientManager.getInstance().NetworkRequestMode("http://zmx.123xk.cn/admin/api.team/entry", params, handler, 3, 404);

    }


    @OnClick({R.id.editor, R.id.add_button})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.editor:

                alert_label(teamExpertise.getText().toString());

                break;
            case R.id.add_button:
                Bundle bundle = new Bundle();
                bundle.putString("team_id", team_id);
                startActivity(SearchDoctorActivity.class, bundle);
                break;
        }
    }

    private String s_value;
    public void alert_label(String text) {

        AlertDialog.Builder builder = new AlertDialog.Builder(mActivity);

        LayoutInflater factory = LayoutInflater.from(this);//提示框
        final View view = factory.inflate(R.layout.dialog_edits, null);//这里必须是final的
        final EditText et = view.findViewById(R.id.editText);
        et.setHint(text);
        builder.setTitle("修改简介");

        final AlertDialog dialog = builder.create();
        dialog.setView(view);

        dialog.setButton(DialogInterface.BUTTON_POSITIVE, "确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });

        dialog.setButton(DialogInterface.BUTTON_NEUTRAL, "取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

                dialog.dismiss();

            }
        });
        dialog.show();
        dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                if (!TextUtils.isEmpty(et.getText().toString())) {

                    s_value = et.getText().toString();
                    teamEdit();
                    dialog.dismiss();

                } else {

                    Toast("非法输入!");

                }


            }
        });


    }


    public void teamEdit() {

        List<String> l = new ArrayList<>();
        l.add(s_value);
        l.add(team_id);

        //请求网络
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("sign", AllUtil.md5(sing(l)));
        params.put("token", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.token, ""));
        params.put("uid", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.uid, ""));
        params.put("ts", System.currentTimeMillis() / 1000); // 当前时间戳
        params.put("cmd", "teamEdit");
        params.put("data[team_id]", team_id);
        params.put("data[describe]", s_value);
        OkHttp3ClientManager.getInstance().NetworkRequestMode("http://zmx.123xk.cn/admin/api.team/entry", params, handler, 4, 404);

    }

}
